package com.authine.cloudpivot.engine.service.bizrule.handler;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.authine.cloudpivot.engine.domain.runtime.BizObject;
import com.authine.cloudpivot.engine.open.service.OpenEngine;
import com.authine.cloudpivot.engine.service.bizrule.handler.context.Request;
import com.authine.lib.utils.IdUtility;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;

public class 智慧工地 extends BaseHandler {
    private static final Logger LOG = LoggerFactory.getLogger("在线编码-基础数据-智慧工地定时任务配置-数据同步");
    private static final String SYSTEM_URL_KEY = "system_url";
    private static final String SYSTEM_ACCOUNT_KEY = "system_account";
    private static final String SYSTEM_PASSWORD_KEY = "system_password";
    private static final String SYSTEM_CXTS_KEY = "cxts";
    private static final String SYSTEM_ZHTBSJ_KEY = "zhtbsj";
    private static final String SYSTEM_LOGIN_PATH = "/ja/Login_auth.do";
    private static final String SYSTEM_ACTION_PATH = "/ja/json.go?action=lbWorker";
    private static final String TARGET_SCHEMA_CODE = "EngineeringProject";

    @Override
    public Object handle(Request req) {
        /* 获取引擎 */
        OpenEngine engine = this.getOpenEngine(req);
        BizObject bizObject = req.getData().getBizObject();
        /* 获取三方系统基本信息 地址 账号 密码 */
        String url = bizObject.getData().get(SYSTEM_URL_KEY).toString();
        String account = bizObject.getData().get(SYSTEM_ACCOUNT_KEY).toString();
        String password = bizObject.getData().get(SYSTEM_PASSWORD_KEY).toString();
        Integer cxts = new BigDecimal(bizObject.getData().get(SYSTEM_CXTS_KEY).toString()).intValue();
        Object zhtbsj = bizObject.getData().get(SYSTEM_ZHTBSJ_KEY);
        /* 登录第三方系统 */
        try {
            OkHttpClient client = new OkHttpClient().newBuilder().cookieJar(new CookieJar() {
                private final Map<String, List<Cookie>> store = new HashMap<>();

                @Override
                public List<Cookie> loadForRequest(HttpUrl url) {
                    List<Cookie> cookies = store.get(url.host());
                    return cookies != null ? cookies : Collections.emptyList();
                }

                @Override
                public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                    store.put(url.host(), cookies);
                }
            }).build();
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            /* 前提条件 登录并处理Session */
            StringBuilder sbdl = new StringBuilder("userName=").append(account).append("&userPass=").append(password);
            okhttp3.Request request = new okhttp3.Request.Builder().url(url + SYSTEM_LOGIN_PATH)
                    .method("POST", RequestBody.create(sbdl.toString(), mediaType))
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            client.newCall(request).execute();
            /* 第一步查询项目信息 */
            StringBuilder sbxm = new StringBuilder("oper=prjQry&pgFrom=0&condi[state]=1&cnt=").append(cxts);
            request = new okhttp3.Request.Builder().url(url + SYSTEM_ACTION_PATH)
                    .method("POST", RequestBody.create(sbxm.toString(), mediaType))
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            Response xmxx = client.newCall(request).execute();
            List<Map<String, Object>> xmxxs = JSON.parseObject(xmxx.body().string()).getObject("list", new TypeReference<List<Map<String, Object>>>() {
            });
            /* 时间不为空则取目标时间到昨天的数据 不取今天目的是预防今天还没完导致数据丢失 */
            if (zhtbsj != null) {
                LocalDate startDate = LocalDate.parse(zhtbsj.toString().substring(0, 10), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                LocalDate endDate = LocalDate.now().minusDays(1);
                xmxxs.removeIf(map -> {
                    LocalDate startdate = LocalDate.parse((String) map.get("startdate"));
                    return startdate.isBefore(startDate) || startdate.isAfter(endDate);
                });
            }
            if (xmxxs != null && !xmxxs.isEmpty()) {
                List<BizObject> datas = new ArrayList<>();
                xmxxs.stream().forEach(item -> {
                    Map<String, Object> data = new HashMap<>();
                    data.put("oldProjectName", item.get("name"));
                    data.put("ProjectNo", item.get("pid"));
                    data.put("TheStartTimeOfTheContract", item.get("startdate"));
                    datas.add(new BizObject(TARGET_SCHEMA_CODE, IdUtility.getUUID(), data));
                });
                List<String> ids = engine.batchCreateBizObjects(datas, true);
                LOG.info("===>>本次新增{}条数据 开始时间: {} 结束时间: {}", ids.size(), zhtbsj, LocalDate.now().minusDays(1));
            } else {
                LOG.info("===>>本次未查询到满足条件的数据 开始时间: {} 结束时间: {}", zhtbsj, LocalDate.now().minusDays(1));
            }
        } catch (IOException e) {
            LOG.error("===>>同步数据出现问题 异常信息：{}", e.getMessage());
        }
        bizObject.getData().put("zhtbsj", LocalDate.now().minusDays(1));
        engine.updateBizObject(bizObject, false);
        return bizObject;
    }
}
